package dev.sharp.ymcloud.cloud;


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import dev.sharp.ymcloud.network.API;
import dev.sharp.ymcloud.network.http.HttpClient;
import dev.sharp.ymcloud.network.http.WsClient;

public class CloudService extends Service {

    private CloudServiceBinder binder;
    private WsClient wsClient;
    private String token;

    public class CloudServiceBinder extends Binder {
        public CloudService getService() {
            return CloudService.this;
        }
    }


    @Override
    public void onCreate() {
        Log.e("CloudService", "WebSocket服务被创建");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("CloudService", "WebSocket服务被启动");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("CloudService", "WebSocket服务被绑定");
        if (binder == null) {
            binder = new CloudServiceBinder();
        }
        return binder;
    }

    @Override
    public void onDestroy() {
        token = null;
        binder = null;
        Log.e("CloudService", "WebSocket服务被释放");
        if (wsClient != null) {
            wsClient.sendMessage("status:service been destried.");
            wsClient.closeConnect();
            wsClient = null;
        }
        super.onDestroy();
    }

    /*
     *重置客户端token
     */
    public void resetToken(String token) {
        if (android.text.TextUtils.isEmpty(token)) {
            if (wsClient != null) {
                Log.e("CloudService", "用户退出登录，关闭连接。");
                wsClient.closeConnect();
                wsClient = null;
            }
        } else {
            if (!token.equals(this.token) || wsClient == null || !wsClient.isWsConnected()) {
                this.token = token;
                refreshConn();
            }
        }
    }

    /*
     *刷新客户端websocket连接
     */
    public void refreshConn() {
        Log.e("CloudService", "刷新连接");
        if (wsClient != null) {
            Log.e("CloudService", "关闭旧连接");
            wsClient.setOnWsMsgListener(null);
            wsClient.closeConnect();
            wsClient = null;
        }
        if (token == null || "".equals(token)) {
            Log.e("CloudService", "token为空");
            return;
        }
        Log.e("CloudService", "新建连接");
        wsClient = HttpClient.wsClient(this, API.getUrl("/ws/").replace("http", "ws") + token);
        wsClient.setOnWsMsgListener((p_wsClient, msg) -> {
            MessageHelper msgHelper = new MessageHelper(p_wsClient);
            msgHelper.setMessage(msg);
        });
        wsClient.openConnect();
    }
}
